package io.renren.modules.sp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sp.dao.SpMatchItemDao;
import io.renren.modules.sp.dao.SpMatchItemTeamDao;
import io.renren.modules.sp.dao.SpTeamDao;
import io.renren.modules.sp.dto.SpTeamDTO;
import io.renren.modules.sp.dto.SpTicketDTO;
import io.renren.modules.sp.entity.SpMatchItemEntity;
import io.renren.modules.sp.entity.SpMatchItemTeamEntity;
import io.renren.modules.sp.entity.SpTeamEntity;
import io.renren.modules.sp.entity.SpUserEntity;
import io.renren.modules.sp.excel.SpTicketExcel;
import io.renren.modules.sp.service.SpMatchItemTeamService;
import io.renren.modules.sp.service.SpTeamUserService;
import io.renren.modules.sp.service.SpTicketService;
import io.renren.modules.sp.service.SpUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
* 参赛证表
*
* @author whc 15953295779@126.com
* @since 3.0 2023-04-21
*/
@RestController
@RequestMapping("sp/spticket")
@Api(tags="参赛证表")
public class SpTicketController {
    @Autowired
    private SpTicketService spTicketService;
    @Autowired
    private SpMatchItemTeamService spMatchItemTeamService;
    @Autowired
    private SpMatchItemDao spMatchItemDao;
    @Autowired
    private SpMatchItemTeamDao spMatchItemTeamDao;

    @Autowired
    private SpUserService spUserService;
    @Autowired
    private SpTeamDao spTeamDao;
    @Autowired
    private SpTeamUserService spTeamUserService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("sp:spticket:page")
    public Result<PageData<SpTicketDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<SpTicketDTO> page = spTicketService.page(params);

        return new Result<PageData<SpTicketDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("sp:spticket:info")
    public Result<SpTicketDTO> get(@PathVariable("id") Long id){
        SpTicketDTO data = spTicketService.get(id);

        return new Result<SpTicketDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("sp:spticket:save")
    public Result save(@RequestBody SpTicketDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        spTicketService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("sp:spticket:update")
    public Result update(@RequestBody SpTicketDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        spTicketService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sp:spticket:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        spTicketService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("sp:spticket:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SpTicketDTO> list = spTicketService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "参赛证表", list, SpTicketExcel.class);
    }

    /**
     * 参赛证查询
     * @param params
     * @return
     */
    @GetMapping("queryTicketBy")
    public Result<PageData<Map>> queryTicketBy(@ApiIgnore @RequestParam Map<String, Object> params){

        PageData<Map> page = spTicketService.queryTicketBy(params);

        return new Result<PageData<Map>>().ok(page);
    }

    /**
     * 下载参赛证、号码布
     */
    @GetMapping("/downloadFile")
    @LogOperation("下载参赛证、号码布")
    public Result<String> downloadFile(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        return spMatchItemTeamService.downloadFile(params,response);
    }

    /**
     * 荣誉证书
     */
    @GetMapping("queryCertificate")
    public Result<PageData<Map>> queryCertificate(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<Map> page = spMatchItemTeamService.queryCertificate(params);
        return new Result<PageData<Map>>().ok(page);
    }

    /**
     * 下载荣誉证书
     */
    @GetMapping("/downloadCertificate")
    @LogOperation("下载荣誉证书")
    public Result<String> downloadCertificate(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        return spMatchItemTeamService.downloadCertificate(params,response);
    }


    /**
     * 生成参赛编号
     * @param
     * @return
     */
    @GetMapping("rebuild")
    @LogOperation("生成参赛编号")
    public Result<SpTeamDTO> rebuild(@ApiIgnore @RequestParam Map<String, Object> params){
        String phone = (String)params.get("phone");
        //根据手机号查询
        List<SpUserEntity> userList = spUserService.queryList(new QueryWrapper<SpUserEntity>().eq("phone",phone));
        if(userList.size()==0){
            return new Result<SpTeamDTO>().error("手机号不存在");
        }
        if(userList.size()>1){
            return new Result<SpTeamDTO>().error("手机号重复");
        }
        Long userId = userList.get(0).getId();
        // 根据创建人查询代表队
        List<SpTeamEntity> teamList = spTeamDao.selectList(new QueryWrapper<SpTeamEntity>().eq("creator",userId));
        if(teamList.size()==0){
            return new Result<SpTeamDTO>().error("代表队不存在");
        }
        if(teamList.size()>1){
            return new Result<SpTeamDTO>().error("代表队重复");
        }
        // 删除所有的参赛证
        spTicketService.deleteByTeamId(teamList.get(0).getId());

        // 查询审核通过的数据 1,2,4,5,6
        // 0审核中 1报名成功 2完赛 3已取消 4比赛中 5已获晋级资格 6晋级成功 7弃权 8驳回 9待确认 10报名未成功
        List<SpMatchItemTeamEntity> matchItemTeamEntityList = spMatchItemTeamDao.selectList(
                new QueryWrapper<SpMatchItemTeamEntity>()
                        .in("status", 1,2,4,5,6)
                        .eq("team_id", teamList.get(0).getId())
        );
        for (SpMatchItemTeamEntity team : matchItemTeamEntityList){
            SpMatchItemTeamEntity entity = spMatchItemTeamService.selectById(team.getId());
            //生成证件
            try {
                String errorMsg = spMatchItemTeamService.generateTicketNo(entity.getId());
                if (StringUtils.isNotBlank(errorMsg)) {
                    System.out.println("生成参赛编号失败:" + errorMsg);
                }
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("生成参赛编号失败:" + e.getMessage());
            }
        }
        return new Result<SpTeamDTO>();
    }

    //查询赛项下参赛编号为空的数据
    @GetMapping("queryNoTicketUser")
    public Result<PageData<Map>> queryNoTicketUser(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<Map> page = spMatchItemTeamService.queryNoTicketUser(params);
        return new Result<PageData<Map>>().ok(page);
    }

    /**
     * 按手机号生成参赛证图片
     * @param
     * @return
     */
    @GetMapping("generateCertificatePic")
    @LogOperation("按手机号生成参赛证图片")
    public Result<String> generateCertificatePic(@ApiIgnore @RequestParam Map<String, Object> params){
        String phone = (String)params.get("phone2");
        if(StringUtils.isBlank(phone)){
            return new Result<String>().error("手机号不能为空");
        }
        List<SpUserEntity> userList =  spUserService.queryList(new QueryWrapper<SpUserEntity>().eq("phone",phone));
        if(userList.size()==0){
            return new Result<String>().error("手机号不存在");
        }
        params.put("userId",userList.get(0).getId());
        spTicketService.generateCertificatePic(params);
        return new Result<String>().ok("生成成功");
    }

    @GetMapping("/download")
    @LogOperation("下载图片")
    public void downloadImage(String imageUrl, String fileName, HttpServletResponse response) throws IOException {
        // 设置下载的文件名称
        if(org.apache.commons.lang.StringUtils.isNotBlank(fileName)) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        } else {
            String imageName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
            response.setHeader("Content-Disposition", "attachment; filename=" + imageName);
        }

        // 打开连接并获取输入流
        URL url = new URL(imageUrl);
        URLConnection connection = url.openConnection();
        InputStream inputStream = connection.getInputStream();

        // 设置下载的文件类型
        response.setContentType(connection.getContentType());
        // 设置下载的文件长度
        response.setContentLength(connection.getContentLength());

        // 将输入流内容写入响应流
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    }



    @GetMapping("genTicketPic")
    @LogOperation("按手机号生成参赛证图片")
    public Result<String> genTicket(@ApiIgnore @RequestParam Map<String, Object> params){
        spTicketService.generateCertificatePic(params);
        return new Result<String>().ok("生成成功");
    }


}
